package handdle

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"ocr/go_client/dto"
	"ocr/go_client/log"
	"ocr/go_client/ocr"
	"sync"
)

var ocrLock sync.Mutex

func Ocr(ctx *gin.Context) {
	ocrLock.Lock()
	defer ocrLock.Unlock()
	req := dto.OcrRequest{}
	err := ctx.ShouldBind(&req)
	if err != nil {
		log.Error("params_err", log.Content{"err": err.Error()})
		response(ctx, nil, err)
		return
	}
	isLocal := false
	if req.ImageBase64 != "" {
		isLocal = true
		req.ImageUrl, err = ocr.SaveBase64Image(req.ImageBase64)
		if err != nil {
			log.Error("imageBase64Err", log.Content{"err": err.Error()})
			response(ctx, nil, err)
			return
		}
	}
	res, err := ocr.Ocr(req.ImageUrl, req.Lang, isLocal, req.IsAngleCls, req.Version)
	if err != nil {
		log.Error("ocr_err", log.Content{"err": err.Error()})
	}
	response(ctx, res, err)
}

func response(ctx *gin.Context, data any, err error) {
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"message": err.Error(),
			"code":    1001,
		})
	} else {
		ctx.JSON(http.StatusOK, gin.H{
			"message": "success",
			"data":    data,
			"code":    0,
		})
	}
	ctx.Abort()
}
